/*
 * @Descripttion:
 * @version:
 * @Author: gengzhi
 * @Date: 2020-08-14 09:58:08
 * @LastEditors: gengzhi
 * @LastEditTime: 2020-08-18 14:41:26
 */
package ddd_application

import (
	"context"
	"encoding/json"
	"fmt"
	"kendoDDD/ddd_domain/protocol"
	"kendoDDD/ddd_infrastructure"
	"kendoDDD/dddcore"
	"log"

	"github.com/astaxie/beego/logs"
)

func fromJSON(c *protocol.SignModel, payload json.RawMessage) error {
	return json.Unmarshal(payload, c)
}

func OnSingnProtocol(es dddcore.EventStore, eb dddcore.EventBus) dddcore.CommandHandler {
	esRepo := ddd_infrastructure.NewESRepository(fmt.Sprintf("%T", protocol.New()), es, eb)
	return func(ctx context.Context, payload []byte, out chan<- dddcore.BusChan) {
		log.Println(string(payload))
		pJs := new(protocol.SignModel)
		fromJSON(pJs, payload)
		p := protocol.New()
		p.SignVm = pJs
		reqSn, err := p.Sign()
		if err != nil {
			out <- dddcore.BusChan{RespMsg: "", ErrMsg: err}
			return
		}
		log.Println(reqSn)
		out <- dddcore.BusChan{RespMsg: reqSn, ErrMsg: nil}
		esRepo.Save(ctx, p)
	}
}

func OnCfrmProtocol(es dddcore.EventStore, eb dddcore.EventBus) dddcore.CommandHandlerMap {
	return func(ctx context.Context, payload map[string]string, out chan<- dddcore.BusChan) {
		beeLog := logs.GetBeeLogger()
		beeLog.Notice("签约确认参数 %v", payload)

		p := protocol.New()
		retStr, err := p.CfrmSign(payload["reqSn"], payload["verCode"])
		if err != nil {
			out <- dddcore.BusChan{RespMsg: "", ErrMsg: err}
			return
		}
		beeLog.Notice(retStr)
		out <- dddcore.BusChan{RespMsg: retStr, ErrMsg: nil}
	}

}

func OnGetProtocolByNo(es dddcore.EventStore, eb dddcore.EventBus) dddcore.CommandHandlerMap {
	return func(ctx context.Context, payload map[string]string, out chan<- dddcore.BusChan) {
		beeLog := logs.GetBeeLogger()
		beeLog.Notice("获取协议信息参数：%v", payload)

		p := protocol.New()
		protocol, err := p.GetInfoByNo(payload["protocolNo"])
		if err != nil {
			out <- dddcore.BusChan{RespMsg: "", ErrMsg: err}
			return
		}
		proJSON, err := json.Marshal(protocol)

		beeLog.Notice("获取协议信息成功！")
		out <- dddcore.BusChan{RespMsg: string(proJSON), ErrMsg: nil}
	}
}
